package org.linlinjava.litemall.wx.web;

import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallCdkey;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallPriceHistory;
import org.linlinjava.litemall.db.service.LitemallCdkeyService;
import org.linlinjava.litemall.db.service.LitemallPriceHistoryService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxCdkeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 礼品券使用历史
 */
@RestController
@RequestMapping("/wx/priceHistory")
@Validated
public class WxPriceHistoryController {
    private final Log logger = LogFactory.getLog(WxPriceHistoryController.class);

    @Autowired
    private LitemallCdkeyService cdkeyService;

    @Autowired
    private WxCdkeyService wxCdkeyService;

    @Autowired
    private LitemallPriceHistoryService priceHistoryService;


    /**
     * 兑换码详情
     *
     * @param userId   用户ID
     * @return 操作结果
     */
    @GetMapping("list")
    public Object list(@LoginUser Integer userId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        List<LitemallPriceHistory> priceHistories = priceHistoryService.querySelective(userId, page, limit, sort, order);
        for (LitemallPriceHistory p: priceHistories
             ) {
            p.setRelationId(priceHistoryService.getTypeString(p));
        }
        PageInfo<LitemallPriceHistory> pagedList = PageInfo.of(priceHistories);

        Map<String, Object> entity = new HashMap<>();
        entity.put("list", priceHistories);
        entity.put("total", pagedList.getTotal());
        entity.put("page", pagedList.getPageNum());
        entity.put("limit", pagedList.getPageSize());
        entity.put("pages", pagedList.getPages());
        return ResponseUtil.ok(entity);
    }

}